<template>
  <div>
    <el-card>
      <div slot="header">
        <div class="flex-x gap-4 pt-2">
          <span>
            <course-select v-model="query.courseId" @change="handleCourseChange"></course-select>
          </span>
          <span>
            <vxe-input v-model="query.keyword" clearable :placeholder="'搜索章节名称'" size="medium"
              @keyup.enter.native="filterByKeyword"></vxe-input>
          </span>
          <span>
            <el-button type="primary" plain size="small" @click="filterByKeyword" icon="el-icon-search"
              :loading="loading">搜索</el-button>
          </span>
          <span class="flex-1"></span>
          <span>
            <el-button type="primary" size="small" @click="handleAdd" icon="el-icon-plus">
              添加章节
            </el-button>
          </span>
        </div>
      </div>

      <!-- Section Table -->
      <vxe-table stripe auto-resize ref="table" :data="sectionList" :loading="loading"
        :custom-config="tableCustomConfig" align="center">
        <vxe-table-column field="id" title="ID" width="60"></vxe-table-column>
        <vxe-table-column field="course.courseName" title="课程" width="200" align="left"></vxe-table-column>
        <vxe-table-column field="sectionName" title="章节名称" width="200"></vxe-table-column>
        <vxe-table-column field="description" title="章节描述" show-overflow></vxe-table-column>
        <vxe-table-column field="sortOrder" title="排序" width="100">
          <template v-slot="{ row }">
            <sort-order-editor :value="row.sortOrder" @update="(newValue) => handleSortUpdate(row, newValue)" />
          </template>
        </vxe-table-column>

        <vxe-table-column field="status" title="状态" width="100">
          <template v-slot="{ row }">
            <el-switch v-model="row.enabled" @change="(enabled) => handleStatusChange(row, enabled)" 
               class="my-2">
              </el-switch>    
          </template>
        </vxe-table-column>
        <vxe-table-column field="gmtCreate" title="创建时间" width="150" :visible="false"/>          
        <vxe-table-column field="gmtModified" title="修改时间" width="150" />
        
        <vxe-table-column title="操作" width="150" fixed="right">
          <template v-slot="{ row }">
            <el-tooltip effect="dark" content="编辑" placement="top">
              <el-button plain circle type="primary" size="mini" icon="el-icon-edit" @click="handleEdit(row)">
              </el-button>
            </el-tooltip>
            <el-tooltip effect="dark" content="删除" placement="top">
              <el-button plain circle type="danger" size="mini" icon="el-icon-delete" @click="handleDelete(row)">
              </el-button>
            </el-tooltip>
            <el-tooltip effect="dark" content="课管理" placement="top">
              <el-button plain circle type="success" size="mini" icon="fa fa-video-camera"
                @click="handleManageLessons(row)">
              </el-button>
            </el-tooltip>
          </template>
        </vxe-table-column>
      </vxe-table>

      <!-- Pagination -->
      <div class="flex-x justify-end mt-4 gap-4">
        <el-pagination class="page" @size-change="handleSizeChange" @current-change="handleCurrentChange"
          :current-page="query.currentPage" :page-sizes="[10, 20, 50, 100]" :page-size="query.limit"
          layout="total, sizes, prev, pager, next, jumper" :total="total"> </el-pagination>
        <el-button circle size="small" @click="handleTableCustom" icon="el-icon-menu"> </el-button>
      </div>

      <!-- Section Dialog -->
      <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="70%" @close="resetForm">
        <el-form :model="sectionForm" :rules="rules" ref="sectionForm" label-width="100px" @submit.native.prevent>
          <el-form-item label="章节名称" prop="sectionName">
            <el-input v-model="sectionForm.sectionName" @keyup.enter.native="submitForm"></el-input>
          </el-form-item>
          <el-form-item label="章节描述" prop="description">
            <Editor v-model="sectionForm.description"></Editor>
          </el-form-item>
          <el-form-item label="排序" prop="sortOrder">
            <el-input-number v-model="sectionForm.sortOrder" :min="0"
              @keyup.enter.native="submitForm"></el-input-number>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="submitForm">确 定</el-button>
        </div>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
import api from '@/common/api';
import CourseSelect from '@/components/admin/CourseSelect';
import Editor from '@/components/admin/Editor.vue';
import SortOrderEditor from '@/components/admin/SortOrderEditor.vue';
import {DEFAULT_TABLE_CUSTOM_CONFIG} from "@/common/constants";

export default {
  name: 'SectionList',
  components: {
    CourseSelect,
    Editor,
    SortOrderEditor
  },
  data() {
    return {
      tableCustomConfig: DEFAULT_TABLE_CUSTOM_CONFIG,

      // List data
      sectionList: [],
      loading: false,
      total: 0,
      query: {
        keyword: '',
        currentPage: 1,
        limit: 10,
        courseId: this.$route.query.courseId || null
      },

      // Dialog data
      dialogVisible: false,
      dialogTitle: '',
      sectionForm: {
        courseId: null,
        sectionName: '',
        description: '',
        sortOrder: 0
      },
      rules: {
        sectionName: [
          {required: true, message: '请输入章节名称', trigger: 'blur'},
          {min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur'}
        ],
        description: [
          {required: false, message: '请输入章节描述', trigger: 'blur'}
        ],
        sortOrder: [
          {required: true, message: '请输入排序序号', trigger: 'blur'}
        ]
      }
    };
  },
  created() {
    this.getSectionList();
  },
  methods: {
    // Handle course change
    handleCourseChange(courseId) {
      this.query.currentPage = 1;
      this.getSectionList();
    },

    // Get section list
    async getSectionList() {
      try {
        this.loading = true;
        const {data} = await api.admin_getCourseSectionList({
          courseId: this.query.courseId,
          currentPage: this.query.currentPage,
          limit: this.query.limit,
          keyword: this.query.keyword
        });
        this.sectionList = data.data.records;
        this.total = data.data.total;
      } catch (error) {
        this.$message.error('获取章节列表失败');
      } finally {
        this.loading = false;
      }
    },

    // Handle pagination
    handleSizeChange(val) {
      this.query.limit = val;
      this.getSectionList();
    },
    handleCurrentChange(val) {
      this.query.currentPage = val;
      this.getSectionList();
    },
    handleTableCustom() {
      this.$refs.table?.openCustom()
    },

    // Handle CRUD operations
    async handleStatusChange(row, enabled) {
      const data = { id: row.id, enabled };
      try {
        await api.admin_saveCourseSection(data);
        this.$message.success(`更新状态成功：已${enabled ? '启用' : '禁用'}`);
        this.getSectionList();
      } catch (error) {
        this.$message.error('更新状态失败');
      }
    },
    handleAdd() {
      if (!this.query.courseId) {
        this.$message.warning('请先选择课程');
        return;
      }
      this.dialogTitle = '添加章节';
      this.sectionForm.courseId = this.query.courseId;
      this.dialogVisible = true;
    },
    handleEdit(row) {
      this.dialogTitle = '编辑章节';
      this.sectionForm = {...row};
      this.dialogVisible = true;
    },
    handleManageLessons(row) {
      this.$router.push({
        name: 'admin-lesson-list',
        query: { courseId: row.courseId, sectionId:row.id }
      });
    },
    async handleDelete(row) {
      try {
        await this.$confirm('确认删除该章节?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        });
        await api.admin_deleteCourseSection(row.id);
        this.$message.success('删除成功');
        this.getSectionList();
      } catch (error) {
        if (error !== 'cancel') {
          this.$message.error('删除失败');
        }
      }
    },

    // Form operations
    submitForm() {
      this.$refs.sectionForm.validate(async (valid) => {
        if (valid) {
          try {
            await api.admin_saveCourseSection(this.sectionForm);
            this.$message.success(this.sectionForm.id ? '更新成功' : '添加成功');
            this.dialogVisible = false;
            this.getSectionList();
          } catch (error) {
            this.$message.error(this.sectionForm.id ? '更新失败' : '添加失败');
          }
        }
      });
    },
    resetForm() {
      this.$refs.sectionForm?.resetFields();
      this.sectionForm = {
        courseId: null,
        sectionName: '',
        description: '',
        sortOrder: 0
      };
    },

    // Filter operations
    filterByKeyword() {
      this.query.currentPage = 1;
      this.getSectionList();
    },

    // Utils
    formatDate(date) {
      return date;
    },

    async handleSortUpdate(row, newValue) {
      try {
        await api.admin_saveCourseSection({
          id: row.id,
          sortOrder: newValue
        });
        this.$message.success('更新排序成功');
        this.getSectionList();
      } catch (error) {
        this.$message.error('更新排序失败');
      }
    }
  }
};
</script>

<style scoped>
.filter-row span {
  margin-right: 20px;
}

.filter-row span button {
  margin-top: 5px;
  margin-bottom: 5px;
}

.filter-row span div {
  margin-top: 8px;
}

.panel-options {
  margin-top: 20px;
  text-align: right;
}

@media screen and (max-width: 768px) {
  .filter-row span {
    margin-right: 5px;
  }

  .filter-row span div {
    width: 80%;
  }
}
</style>
